import React from 'react';
import { Tree, Button } from 'antd';
const TreeNode = Tree.TreeNode;
import {WeaTools, WeaErrorPage, WeaDialog, WeaRightMenu, WeaNewScroll  } from 'ecCom';
class WeaPortalTree extends React.Component{
  constructor(props) {
      super(props);
      this.state = {
          treeData: [],
          saveData: [],
      }
      this.handleSave = this.handleSave.bind(this);
      this.getButtons = this.getButtons.bind(this);
      this.getRightMenu = this.getRightMenu.bind(this);
      this.onRightMenuClick = this.onRightMenuClick.bind(this);
      this.handleCancel = this.handleCancel.bind(this);
      this.onDrop = this.onDrop.bind(this);
      this.setTreeData = this.setTreeData.bind(this);
      this.handleTreeData = this.handleTreeData.bind(this);
  }
  handleTreeData(dataUrl, treeData, reqParams = {}){
      if(dataUrl){
          WeaTools.callApi(dataUrl, 'POST',reqParams).then(data => {
              this.setState({
                  treeData: data,
              });
          });
      }else{
           this.setState({
              treeData: treeData,
           });
      }
  }
  componentWillMount(){
      const { visible, dataUrl, treeData, reqParams } = this.props;
      if(visible) {
          this.handleTreeData(dataUrl, treeData, reqParams);
      }
  }
  componentWillReceiveProps(nextProps){
      const { visible, dataUrl, treeData, reqParams = {} } = nextProps;
      if(visible || this.props.dataUrl !== dataUrl){
          this.handleTreeData(dataUrl, treeData, reqParams);
      }
  }
  handleSave() {
       const { onSave } = this.props; 
       const jsonStr = JSON.stringify(this.state.saveData);
       onSave({jsonStr});
  }
  handleCancel(){
      const { onCancel } = this.props;
      onCancel();
  }
  getButtons(){
      let btns = [];
      btns.push(<Button type="primary" onClick={this.handleSave}>保存</Button>);
      btns.push(<Button onClick={this.handleCancel}>取消</Button>);
      return btns;
  }
  getRightMenu(){
      let btns = [];
      btns.push({
          icon: <i className='icon-coms-Journal'/>,
          content:'保存'
      });
      btns.push({
          icon: <i className='icon-coms-go-back'/>,
          content:'取消'
      });
      return btns
  }
  onRightMenuClick(key){
      switch(key){
          case '0': //保存
              this.handleSave();
              break;
          case '1': //取消
              this.handleCancel();
              break;
      }
  }
  onDrop(info) {
      const dropKey = info.node.props.eventKey;
      const dragKey = info.dragNode.props.eventKey;
      const loop = (data, id, callback) => {
          data.forEach((item, index, arr) => {
              if (item.id === id) {
                  return callback(item, index, arr);
              }
              if (item.children) {
                  return loop(item.children, id, callback);
              }
          });
      };
      const data = [...this.state.treeData];
      let dragObj;
      loop(data, dragKey, (item, index, arr) => {
          arr.splice(index, 1);
          dragObj = item;
      });
      if (info.dropToGap) {
          let ar;
          let i;
          loop(data, dropKey, (item, index, arr) => {
              ar = arr;
              i = index;
          });
          //拖动到目标同级，目标节点的parentId为拖动节点的parentId
          dragObj.parentId = item.parentId;
          ar.splice(i, 0, dragObj);
      } else {
          loop(data, dropKey, (item) => {
              item.children = item.children || [];
              //拖动到目标子级，目标节点的id为拖动节点的parentId
              dragObj.parentId = item.id;
              item.children.push(dragObj);
          });
      }
      this.setTreeData(data);
  }
  setTreeData(treeData = []){
      let saveData = [];
      let index = 1;
      const addSaveData = (pid, data = []) => data.map(item=>{
          if(item){
              saveData.push({
                  id: item.id,
                  pid: pid,
                  sort: index,
              });
              index += 1;
              if(item.children && item.children.length){
                  addSaveData(item.id, item.children);
              } 
          }
      });
      addSaveData('0', treeData);
      this.setState({
          treeData,
          saveData,
      });
  }
  render(){
    const { visible, title, style } = this.props;
    let dialogStyle = style ? style : {width:top.document.body.clientWidth*0.4,height:top.document.body.clientHeight*0.6}; 
    const loop = data => data.map((item) => {
        if (item.children && item.children.length) {
            return <TreeNode key={item.id} title={item.name}>{loop(item.children)}</TreeNode>;
        }
        return <TreeNode key={item.id} title={item.name}/>;
    });
    return <WeaDialog title={title}
                visible={visible} 
                closable={true}
                onCancel={this.handleCancel}
                icon='icon-coms-portal'
                iconBgcolor='#1a57a0'
                maskClosable={false}
                buttons={this.getButtons()}
                style={dialogStyle}>
                <WeaRightMenu datas={this.getRightMenu()} onClick={this.onRightMenuClick}>
                    <div style={{padding:'10px'}}>
                        <WeaNewScroll scrollId="mainpagepageorder" height={dialogStyle.height}>
                            <Tree draggable onDrop={this.onDrop}>{loop(this.state.treeData)}</Tree>
                        </WeaNewScroll>
                    </div>
                </WeaRightMenu>
        </WeaDialog>
  }
}
class MyErrorHandler extends React.Component {
    render() {
        const hasErrorMsg = this.props.error && this.props.error !== "";
            return ( <WeaErrorPage msg = { hasErrorMsg ? this.props.error : "对不起，该页面异常，请联系管理员！" }/>
        );
    }
}
WeaPortalTree = WeaTools.tryCatch(React, MyErrorHandler, { error: "" })(WeaPortalTree);
export default WeaPortalTree;

